package com.zlm.hp.receiver;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;

import com.zlm.hp.manager.AudioPlayerManager;

/**
 * 来电/耳机拔出时暂停播放
 * see: https://github.com/ocwvar/DarkPurple/blob/master/app/src/main/java/com/ocwvar/darkpurple/Services/AudioService.java
 */
public class NoisyAudioStreamReceiver {

    private BroadcastReceiver receiver;
    private final IntentFilter filter;
    private final BluetoothAdapter bluetoothAdapter;

    public NoisyAudioStreamReceiver() {
        filter = new IntentFilter();
        filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY); //有线耳机拔出变化
        filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); //蓝牙耳机连接变化

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    /**
     * 注册广播
     * @param context
     */
    public void registerReceiver(Context context) {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
                    AudioPlayerManager.newInstance(context).pause();
                }
                //蓝牙耳机断开连接 同时当前音乐正在播放
                if(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(intent.getAction()) &&
                        BluetoothProfile.STATE_DISCONNECTED == bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET)) {
                    AudioPlayerManager.newInstance(context).pause();
                }

            }
        };
        context.registerReceiver(receiver, filter);
    }

    /**
     * 取消注册广播
     */
    public void unregisterReceiver(Context context) {
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }

    public IntentFilter getFilter() {
        return filter;
    }

}
